import { ERRCODE } from "@/const/new";
import axios from "axios";

interface IAnyObj {
  [index: string]: unknown;
}

type Fn = (data: FcResponse<any>) => unknown;

class Request {
  baseURL;
  constructor() {
    if (process.env.NODE_ENV === "production") {
      this.baseURL = process.env.NEXT_PUBLIC_BASEURL;
    } else {
      this.baseURL = "开发的地址";
    }
    this.interceptor();
  }
  get(params: IAnyObj = {}, clearFn?: Fn) {
    new Promise((resolve) => {
      axios
        .get(this.baseURL as string, { params })
        .then((result) => {
          let res;
          if (clearFn !== undefined) {
            res = clearFn(result.data) as unknown as FcResponse<T>;
          } else {
            res = result.data as FcResponse<T>;
          }
          resolve([null, res as FcResponse<T>]);
        })
        .catch((err) => {
          resolve([err, undefined]);
        });
    });
  }
  handleNetworkError(errStatus) {
    let errMessage = "未知错误";
    if (errStatus) {
      if (ERRCODE[errStatus]) {
        errMessage = ERRCODE[errStatus];
      } else {
        errMessage = `其他连接错误 --${errStatus}`;
      }
    } else {
      errMessage = `无法连接到服务器！`;
    }
    message.error(errMessage);
  }
  interceptor() {
    axios.interceptors.response.use();
    axios.interceptors.request.use();
  }
}

export default Request;
